package com.ok.common.ext

import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView

/**
 * 是否在顶部
 */
fun RecyclerView.isTop(): Boolean {
    return !this.canScrollVertically(-1)
}

/**
 * 滑动后自动返回到顶部
 */
fun RecyclerView.addAutoScrollTopListener(autoScrollDelay: Long = 10000) {
    val autoScrollRunnable = Runnable { this.scrollToPosition(0) }
    this.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
            if (newState == RecyclerView.SCROLL_STATE_DRAGGING) {
                recyclerView.removeCallbacks(autoScrollRunnable)
            }
        }

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            recyclerView.removeCallbacks(autoScrollRunnable)
            recyclerView.postDelayed(autoScrollRunnable, autoScrollDelay)
            if (recyclerView.isTop()) {
                recyclerView.removeCallbacks(autoScrollRunnable)
            }
        }
    })
}

/**
 * RecyclerView扩展函数，用于监听滑动到底部事件。
 *
 * @param onBottomReached 一旦RecyclerView滑动到底部，将触发此函数。
 */
fun RecyclerView.onScrollToBottom(
    onBottomReached: () -> Unit
) {
    this.addOnScrollListener(object : RecyclerView.OnScrollListener() {
        private var loading = true // 防止多次加载的标志

        override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
            super.onScrolled(recyclerView, dx, dy)

            val layoutManager = recyclerView.layoutManager
            val visibleItemCount = layoutManager?.childCount ?: 0
            val totalItemCount = layoutManager?.itemCount ?: 0
            val firstVisibleItemPosition = when (layoutManager) {
                is LinearLayoutManager -> layoutManager.findFirstVisibleItemPosition()
                is GridLayoutManager -> layoutManager.findFirstVisibleItemPosition()
                else -> return
            }

            if (!loading && (visibleItemCount + firstVisibleItemPosition) >= totalItemCount
                && firstVisibleItemPosition >= 0
            ) {
                loading = true
                onBottomReached.invoke() // 触发底部到达事件
            } else if ((visibleItemCount + firstVisibleItemPosition) < totalItemCount) {
                loading = false // 重置加载标志，允许再次加载
            }
        }
    })
}






